package com.example.myys.network.ysPlugins

import com.alibaba.fastjson2.JSONObject
import com.example.myys.common.DataSource
import com.example.myys.data.entity.ChapterBean
import com.example.myys.data.entity.DataBean
import com.example.myys.network.HttpClient
import com.example.myys.network.PluginInterface
import org.jsoup.Jsoup
import org.jsoup.nodes.Element

//插件实现
class PluginWanJiaYinShi : PluginInterface {
    override suspend fun getRecommend(
        baseUrl: String,
        type: String,
        rules: JSONObject
    ): List<DataBean> {
        val dataBeanList = arrayListOf<DataBean>()
        val url = rules.getString("url") //获取链接
        val html = HttpClient.get(url) //获取页面
        if (html == null) {
            return dataBeanList;
        }
        val jsoupHtml = Jsoup.parse(html) //解析页面
        val listCssPath = rules.getString("listCssPath") //列表css规则
        val listHtml = jsoupHtml.select(listCssPath)
        val listItemCssPath = rules.getString("listItemCssPath") //列表项css规则
        val listItemsHtml = listHtml.select(listItemCssPath)
        val itemRules = rules.getJSONObject("item")
        for (item in listItemsHtml) {
            val dataBean = setDataBean(DataBean(), item, itemRules, type)
            dataBeanList.add(dataBean)
        }
        return dataBeanList
    }

    override suspend fun getCategorize(
        baseUrl: String,
        categorizeName: String,
        type: String,
        page: Int,
        rules: JSONObject
    ): List<DataBean> {
        val dataBeanList = arrayListOf<DataBean>()
        val urls = rules.getJSONArray("urls") //获取链接
        val urlitems =
            urls.filter { url -> JSONObject.from(url).getString("name") == categorizeName }
        if (urlitems.isEmpty()) {
            return dataBeanList
        }
        val url = JSONObject.from(urlitems[0]).getString("url")
        val html = HttpClient.get(url) //获取页面
        if (html == null) {
            return dataBeanList;
        }
        val jsoupHtml = Jsoup.parse(html) //解析页面
        val listCssPath = rules.getString("listCssPath") //列表css规则
        val listHtml = jsoupHtml.select(listCssPath)
        val listItemCssPath = rules.getString("listItemCssPath") //列表项css规则
        val listItemsHtml = listHtml.select(listItemCssPath)
        val itemRules = rules.getJSONObject("item")
        for (item in listItemsHtml) {
            val dataBean = setDataBean(DataBean(), item, itemRules, type)
            dataBeanList.add(dataBean)
        }
        return dataBeanList
    }

    override suspend fun getSearchKeyWord(
        baseUrl: String,
        type: String,
        keyword: String,
        rules: JSONObject
    ): List<DataBean> {
        val dataBeanList = arrayListOf<DataBean>()
        var url = rules.getString("url") //获取链接
        if (url.isBlank()) {
            return dataBeanList
        }
        url = url.replace(":keyWord", keyword)
        val html = HttpClient.get(url) //获取页面
        if (html == null) {
            return dataBeanList;
        }
        val jsoupHtml = Jsoup.parse(html) //解析页面
        val listCssPath = rules.getString("listCssPath") //列表css规则
        val listHtml = jsoupHtml.select(listCssPath)
        val listItemCssPath = rules.getString("listItemCssPath") //列表项css规则
        val listItemsHtml = listHtml.select(listItemCssPath)
        val itemRules = rules.getJSONObject("item")
        for (item in listItemsHtml) {
            val dataBean = setDataBean(DataBean(), item, itemRules, type)
            dataBeanList.add(dataBean)
        }
        return dataBeanList
    }

    override suspend fun getDetails(
        baseUrl: String,
        dataBean: DataBean,
        rules: JSONObject
    ): DataBean {
        var detailUrl = dataBean.url
        if (!detailUrl.startsWith("http")) {
            detailUrl = baseUrl + detailUrl
        }
        val html = HttpClient.get(detailUrl) //获取页面
        if (html == null) {
            return dataBean;
        }
        val jsoupHtml = Jsoup.parse(html) //解析页面
        val dataBeanDetails = setDataBean(dataBean, jsoupHtml, rules, dataBean.type)
        val dataSourceJsonArray = rules.getJSONArray("datasource")
        if (dataSourceJsonArray.isNotEmpty()) {
            val dataSourceList = arrayListOf<DataSource>()
            for ((index, dataSourceJson) in dataSourceJsonArray.withIndex()) {
                val dataSource = DataSource()
                val dataSourceJSONObject = JSONObject.from(dataSourceJson)
                dataSource.name = dataSourceJSONObject.getString("name")
                dataSource.index = index
                val listCssPath = dataSourceJSONObject.getString("listCssPath")
                val listItemCssPath = dataSourceJSONObject.getString("listItemCssPath")
                val itemJson = dataSourceJSONObject.getJSONObject("item")
                val listItem = jsoupHtml.select(listCssPath).select(listItemCssPath)
                val episodes = arrayListOf<ChapterBean>()
                for ((index, item) in listItem.withIndex()) {
                    val dataEpisodes = ChapterBean()
                    val nameCssPath = itemJson.getList("nameCssPath", String::class.java)
                    if (nameCssPath[0].isNotBlank()) {
                        dataEpisodes.name = item.select(nameCssPath[0]).text()
                    }
                    val urlCssPath = itemJson.getList("urlCssPath", String::class.java)
                    if (urlCssPath[0].isNotBlank()) {
                        dataEpisodes.url = item.select(urlCssPath[0]).attr(urlCssPath[1])
                    }
                    dataEpisodes.index = index
                    episodes.add(dataEpisodes)
                }
                dataSource.episodes = episodes
                dataSourceList.add(dataSource)
            }
            dataBeanDetails.dataSource = dataSourceList
        }
        return dataBeanDetails
    }

    override suspend fun getContent(baseUrl: String, url: String, rules: JSONObject): String {
        var content = ""
        var contentUrl = url
        if (!contentUrl.startsWith("http")) {
            contentUrl = baseUrl + contentUrl
        }
        val contentCssPath = rules.getList("contentCssPath", String::class.java)
        if (contentCssPath[0].isBlank()) {
            return contentUrl
        }
        val html: String? = HttpClient.get(contentUrl) //获取页面
        if (html == null) {
            return content
        }
        val jsoupHtml = Jsoup.parse(html) //解析页面
        if (contentCssPath[0].isNotBlank()) {
            if (contentCssPath[1].isBlank()) {
                content = jsoupHtml.select(contentCssPath[0]).attr(contentCssPath[1])
            } else {
                val contentText = jsoupHtml.select(contentCssPath[0]).html()
                val regex = Regex(contentCssPath[1])
                val matchResult = regex.find(contentText)
                if (matchResult != null) {
                    content = matchResult.groupValues[0].replace("\\", "")
                }
            }
        }
        return content
    }

    fun setDataBean(
        dataBean: DataBean = DataBean(),
        item: Element,
        itemRules: JSONObject,
        type: String
    ): DataBean {
        val nameCssPath = itemRules.getList("nameCssPath", String::class.java)
        if (dataBean.name.isBlank() && nameCssPath[0].isNotBlank()) {
            dataBean.name = item.select(nameCssPath[0]).text()
        }
        val imageCssPath = itemRules.getList("imageCssPath", String::class.java)
        if (dataBean.cover.isBlank() && imageCssPath[0].isNotBlank()) {
            dataBean.cover = item.select(imageCssPath[0]).attr(imageCssPath[1])
        }
        val urlCssPath = itemRules.getList("urlCssPath", String::class.java)
        if (dataBean.url.isBlank() && urlCssPath[0].isNotBlank()) {
            dataBean.url = item.select(urlCssPath[0]).attr(urlCssPath[1])
        }
        val briefCssPath = itemRules.getList("briefCssPath", String::class.java)
        if (dataBean.desc.isBlank() && briefCssPath[0].isNotBlank()) {
            dataBean.desc = item.select(briefCssPath[0]).text()
        }
        val stateCssPath = itemRules.getList("stateCssPath", String::class.java)
        if (dataBean.status.isBlank() && stateCssPath[0].isNotBlank()) {
            dataBean.status = item.select(stateCssPath[0]).text()
        }
        val publisDateCssPath = itemRules.getList("publisDateCssPath", String::class.java)
        if (dataBean.releaseTime.isBlank() && publisDateCssPath[0].isNotBlank()) {
            dataBean.releaseTime = item.select(publisDateCssPath[0]).text()
        }
        val updateDateCssPath = itemRules.getList("updateDateCssPath", String::class.java)
        if (dataBean.updateTime.isBlank() && updateDateCssPath[0].isNotBlank()) {
            dataBean.updateTime = item.select(updateDateCssPath[0]).text()
        }
        dataBean.type = type
        return dataBean
    }
}